package com.pojo;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.List;

public class Dom4jTest {
    @Test
    public void test1() throws Exception {
        //创建一个SAXReader输入柳，去读取xml配置文件，生成Document对象
        SAXReader saxReader= new SAXReader();
        Document document = saxReader.read("src/books.xml");
        System.out.println(document);
    }

    //读取books.xml文件生成book类
    @Test
    public void test() throws Exception {


        //3、通过根元素获取book标签对象
        //遍历，处理每个book标签转换为book类
        SAXReader saxReader=new SAXReader();
        //在junit测试中，相对路径是从模块名开始算
        Document document = saxReader.read("src/books.xml");//1、读取books.xml文件

        Element rootElement = document.getRootElement();//2、通过文档对象获取根元素
        //System.out.println(rootElement);
        // org.dom4j.tree.DefaultElement@71dac704 [Element: <books attributes: []/>]

        //element()和elements()都是通过标签名查找子元素
        List<Element> books = rootElement.elements("book");
        for (Element book:books){
            //asXML() 把标签对象转化为标签字符串
            //System.out.println(book.asXML());
            Element nameElement = book.element("name");
//            System.out.println(nameElement.asXML());
            //getText()可以获取标签中的文本内容
            String nameText = nameElement.getText();
//            System.out.println(nameText);

            //直接获取标签名的文本内容
            String priceText = book.elementText("price");
//            System.out.println(priceText);
            String authorText = book.elementText("author");

            //获取属性值
            String snValue = book.attributeValue("sn");
            System.out.println(new book(snValue,nameText,Double.parseDouble(priceText),authorText));
        }
    }
}
